package service

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"grpc/basic/global"
	__ "grpc/basic/proto"
	"grpc/handle/model"
	"grpc/pkg"
	"log"
	"strconv"
	"sync"
	"time"
)

func (s *Server) AddVideo(_ context.Context, in *__.AddVideoReq) (*__.AddVideoResp, error) {
	var video model.Video

	video = model.Video{
		UserId:     int(in.UserId),
		Title:      in.Title,
		Content:    in.Content,
		Image:      in.Image,
		Types:      in.Types,
		Permission: in.Permission,
	}

	if err := video.AddVideo(global.DB); err != nil {
		return nil, fmt.Errorf("发布失败")
	}

	return &__.AddVideoResp{
		Greet:   "视频发布成功",
		VideoId: int64(video.ID),
	}, nil
}

func (s *Server) ListVideo(_ context.Context, in *__.ListVideoReq) (*__.ListVideoResp, error) {
	var video model.Video

	listVideo, err := video.ListVideo(global.DB, in.Code)
	if err != nil {
		return nil, fmt.Errorf("查询失败")
	}

	marshal, err := json.Marshal(listVideo)
	if err != nil {
		return nil, err
	}

	global.Rdb.Set(global.Ctx, "ListVideo", marshal, time.Minute*10)

	return &__.ListVideoResp{
		Greet: "查询成功",
		List:  listVideo,
	}, nil
}

func (s *Server) VideoList(_ context.Context, in *__.VideoListReq) (*__.VideoListResp, error) {
	var video model.Video

	list, err := video.VideoList(global.DB)
	if err != nil {
		return nil, fmt.Errorf("详情展示失败")
	}

	//es同步
	var wg sync.WaitGroup
	for _, v := range list {
		wg.Add(1)

		go func(video *__.VideoList) {
			defer wg.Done()

			// Build the request body.
			data, err := json.Marshal(video)
			if err != nil {
				log.Fatalf("Error marshaling document: %s", err)
			}

			// Set up the request object.
			req := esapi.IndexRequest{
				Index:      "yyy_test",
				DocumentID: strconv.Itoa(int(video.VideoId)),
				Body:       bytes.NewReader(data),
				Refresh:    "true",
			}

			// Perform the request with the client.
			res, err := req.Do(context.Background(), global.Ela)
			if err != nil {
				log.Fatalf("Error getting response: %s", err)
			}
			defer res.Body.Close()

		}(v)
	}
	wg.Wait()

	return &__.VideoListResp{
		Greet: "详情展示成功",
		List:  list,
	}, nil
}

func (s *Server) ListEpisode(_ context.Context, in *__.ListEpisodeReq) (*__.ListEpisodeResp, error) {
	var video model.Episode

	episode, err := video.ListEpisode(global.DB)
	if err != nil {
		return nil, fmt.Errorf("剧集详情展示失败")
	}

	return &__.ListEpisodeResp{
		Greet: "剧集详情展示成功",
		List:  episode,
	}, nil
}

func (s *Server) AddHistory(_ context.Context, in *__.AddHistoryReq) (*__.AddHistoryResp, error) {
	var video model.History

	video = model.History{
		VideoId:    int(in.VideoId),
		Season:     in.Season,
		Collection: in.Collection,
		Watch:      int(in.Watch),
	}

	if err := video.AddHistory(global.DB); err != nil {
		return nil, err
	}

	return &__.AddHistoryResp{
		Greet: "历史记录添加成功",
		Id:    int64(video.ID),
	}, nil
}

func (s *Server) ListHistory(_ context.Context, in *__.ListHistoryReq) (*__.ListHistoryResp, error) {
	var video model.History

	history, err := video.ListHistory(global.DB, in.Page, in.Size)
	if err != nil {
		return nil, fmt.Errorf("历史记录列表展示失败")
	}

	return &__.ListHistoryResp{
		Greet: "历史记录列表",
		List:  history,
	}, nil
}

func (s *Server) AddFavorite(_ context.Context, in *__.AddFavoriteReq) (*__.AddFavoriteResp, error) {
	var video model.Favorite
	video = model.Favorite{
		UserId:  int(in.UserId),
		VideoId: int(in.VideoId),
		Status:  in.Status,
	}

	if err := video.AddFavorite(global.DB); err != nil {
		return nil, fmt.Errorf("收藏失败")
	}

	return &__.AddFavoriteResp{
		Page: "收藏成功",
		Id:   int64(video.ID),
	}, nil
}

func (s *Server) ListFavorite(_ context.Context, in *__.ListFavoriteReq) (*__.ListFavoriteResp, error) {
	var video model.Favorite

	favorite, err := video.ListFavorite(global.DB)
	if err != nil {
		return nil, fmt.Errorf("展示失败")
	}

	marshal, err := json.Marshal(favorite)
	if err != nil {
		return nil, err
	}

	global.Rdb.Set(global.Ctx, "ListFavorite", marshal, time.Minute*10)

	return &__.ListFavoriteResp{
		Page: "收藏列表",
		List: favorite,
	}, nil
}

func (s *Server) ListMemBer(_ context.Context, in *__.ListMemBerReq) (*__.ListMemBerResp, error) {
	var video model.MemBer

	if err := video.ListMemBer(global.DB, in.Id); err != nil {
		return nil, fmt.Errorf("失败")
	}

	return &__.ListMemBerResp{
		UserId:     strconv.Itoa(video.UserId),
		VideoId:    strconv.Itoa(video.VideoId),
		Title:      video.Title,
		Prone:      video.Prone,
		Permission: video.Permission,
		Status:     video.Status,
	}, nil
}

func (s *Server) AliPay(_ context.Context, in *__.AliPayReq) (*__.AliPayResp, error) {
	var video model.Order

	pay, err := pkg.AliPay(video.OrderSn, video.Prone)
	if err != nil {
		return nil, err
	}

	return &__.AliPayResp{
		Pag:    "成功",
		Alipay: pay,
	}, nil
}

func (s *Server) AddLike(_ context.Context, in *__.AddLikeReq) (*__.AddLikeResp, error) {
	var video model.Like

	video = model.Like{
		UserId:  int(in.UserId),
		VideoId: int(in.VideoId),
		Pid:     int(in.Pid),
		Runt:    in.Runt,
	}

	if err := video.AddLike(global.DB); err != nil {
		return nil, fmt.Errorf("添加失败")
	}

	marshal, err := json.Marshal(video)
	if err != nil {
		return nil, err
	}

	global.Rdb.Set(global.Ctx, "video", marshal, time.Minute*10)

	return &__.AddLikeResp{
		Pag: "评论成功",
	}, nil
}
